import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:video_player/video_player.dart';
import 'package:yp/config/event_bus.dart';
import 'package:connectivity/connectivity.dart';
import 'FullScreen.dart';
import 'LoadView.dart';

class VideoPlayerPlus extends StatefulWidget {
  final VideoPlayerController controller;

  const VideoPlayerPlus(
    this.controller, {
    Key key,
  }) : super(key: key);

  @override
  _VideoPlayerPlusState createState() => _VideoPlayerPlusState();
}

class _VideoPlayerPlusState extends State<VideoPlayerPlus> {
  VideoPlayerController _controller;
  bool xianshikz = false;
  bool _play = false;
  bool _volume = false;
  var initialize;
  var dura;//视频播放比
  var xianshi;//现时
  var zongshic;//总时长
  Function _function;

  @override
  void initState() {
    super.initState();
    _controller = widget.controller;
    _function = () {
      var duration = _controller.value.duration;
      var position = _controller.value.position;
      if (position.inMilliseconds > 0 && duration.compareTo(position) == 0) {
        setState(() {
          _play = false;
        });
      }
    };
    _controller.addListener(_function);

    initialize = _controller.initialize().then((a)async{
      var connectivityResult = await (Connectivity().checkConnectivity());
      if (connectivityResult == ConnectivityResult.mobile) {
        print("手机流量");
        setState(() {
          _play = false;
        });
      } else if (connectivityResult == ConnectivityResult.wifi) {
        print('WiFi热点');
        setState(() {
          _controller.play();
          _play = true;
        });
      }
      _controller.setVolume(0);
    });
     //执行监听，只要有内容就会刷新
    _controller.addListener(() {
      setState(() {
        xianshi = _controller.value.position.inSeconds;//现时
        zongshic = _controller.value.duration.inSeconds;//总时长
        //进度条的播放进度，用当前播放时间除视频总长度得到
        dura=xianshi/zongshic;
      });
    });
    eventBus.on<PlayVideoEvent>().listen((event) {
      if (!event.play) {
         //_controller.pause();
         // _controller.seekTo(_controller.value.duration*0); //设置视频播放位置跳转至指定时间（duration类型）

      }
    });
  }
  shijian(time){
    var s = time%60;
    if (s<10) {
      s = '0${s}';
    }
    return s;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 750.w,
      color: Colors.black,
      child: FutureBuilder(
          future: initialize,
          builder: (BuildContext context, AsyncSnapshot snapshot,) {
            //请求完成
            if (snapshot.connectionState == ConnectionState.done) {
              //发生错误
              if (snapshot.hasError) {
                debugPrint(snapshot.error.toString());
                _controller.dispose();
                return Center(
                    child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    IconButton(
                        icon: Icon(
                          Icons.error_outline,
                          color: Colors.white,
                        ),
                        onPressed: () {
                          setState(() {
                            initialize = _controller.initialize();
                          });
                        }),
                    Text(
                      "视频加载失败",
                      style: TextStyle(color: Colors.white),
                    )
                  ],
                ));
              }
              return Stack(
                children: <Widget>[
                  Center(
                      child: Container(
                    // width: geWidth(_controller.value),
                    //填充
                    width: double.infinity,
                    height: 375.r,
                    child: GestureDetector(
                      child: _controller.value.isInitialized
                          ? AspectRatio(
                              aspectRatio: _controller.value.aspectRatio,
                              child: VideoPlayer(_controller))
                          : Container(),
                      onTap: () {
                        xianshikz = !xianshikz;
                        // _controller.pause();
                        setState(() {});
                      },
                    ),
                  )),
                  // Visibility(
                  //   child: Container(
                  //     height: 375.r,
                  //     child: Center(
                  //     child: IconButton(
                  //         icon: Icon(
                  //           Icons.play_circle_outline,
                  //           size: 40,
                  //           color: Color(0xffd5d0d0),
                  //         ),
                  //         onPressed: () {
                  //           _play = true;
                  //           var duration = _controller.value.duration;
                  //           var position = _controller.value.position;
                  //           if (position.inMilliseconds > 0 &&
                  //               duration.compareTo(position) == 0) {
                  //             setState(() {
                  //               _controller.seekTo(Duration());
                  //             });
                  //             return;
                  //           }
                  //           _controller.play();
                  //           setState(() {});
                  //         }),
                  //   ),
                  //   ),
                  //   visible: !_play,
                  // ),
                  Positioned(
                    child:Visibility(
                    child: Row(
                      children: [
                        Text(
                          '${_controller.value.position.inMinutes}:${shijian(xianshi)}',
                          style: TextStyle(
                            color: Colors.white,
                          ),
                        ),
                        // //视频进度条
                        Container(
                          width: MediaQuery.of(context).size.width*0.4,
                          child: SliderTheme(
                          data: SliderTheme.of(context).copyWith(
                              trackShape:null, //轨道的形状
                              trackHeight: 2, //trackHeight：滑轨的高度
                              activeTrackColor: Colors.white, //已滑过轨道的颜色
                              inactiveTrackColor: Color(0xffd5d0d0),//未滑过轨道的颜色
                              thumbColor: Colors.white, //滑块中心的颜色（小圆头的颜色）
                              overlayColor: Colors.white, //滑块边缘的颜色
                              thumbShape: RoundSliderThumbShape(//可继承SliderComponentShape自定义形状
                                 disabledThumbRadius: 15, //禁用时滑块大小
                                 enabledThumbRadius: 4, //滑块大小
                              ),
                            overlayShape: RoundSliderOverlayShape(//可继承SliderComponentShape自定义形状
                              overlayRadius: 14, //滑块外圈大小
                            ),
                          ),
                          child:  Slider(
                            value: dura,//当前值,拖动时会把值传回来
                            max: 1.0,//最大值：double类型
                            min: 0.0, //最小值：double类型
                            //滑动过程中执行的方法
                            onChanged: (double val) {
                              this.setState(() {
                                dura = val;
                                var sj = _controller.value.duration*dura;
                                _controller.seekTo(sj); //设置视频播放位置跳转至指定时间（duration类型）
                              });
                            },            
                          ),
                        ),
                        ),
                        Text(
                          "${_controller.value.duration.inMinutes}:${shijian(zongshic)}",
                          style: TextStyle(
                            color: Colors.white,
                          ),
                        ),
                        // IconButton(
                        // icon: Icon(
                        //   _volume ? Icons.volume_up : Icons.volume_off,
                        //   color: Colors.white,
                        // ),
                        // onPressed: () {
                        //   setState(() {
                        //     if (_volume)
                        //       _controller.setVolume(0);
                        //     else
                        //       _controller.setVolume(1);
                        //     _volume = !_volume;
                        //   });
                        // }),
                        // IconButton(
                        // icon: Icon(
                        //   Icons.fullscreen,
                        //   color: Colors.white,
                        // ),
                        // onPressed: () {
                        //   _controller.pause();
                        //   Navigator.push(context,
                        //       MaterialPageRoute(builder: (context) {
                        //     return FullScreen(
                        //       controller: _controller,
                        //       play: _play == true,
                        //     );
                        //   }));
                        // }),
                      ],
                    ),
                    visible: !xianshikz,
                  ),
                    bottom: 15,
                    left: 40,
                  ),
                  Positioned(
                    child:Visibility(
                    child: IconButton(
                        icon: Icon(
                          _play ? Icons.pause:Icons.play_arrow,
                          color: Colors.white,
                        ),
                        onPressed: () {
                          if (!_play) {
                            var duration = _controller.value.duration;
                            var position = _controller.value.position;
                            if (position.inMilliseconds > 0 &&
                                duration.compareTo(position) == 0) {
                              setState(() {
                                _controller.seekTo(Duration());
                              });
                              return;
                            }
                            _controller.play();
                          }else{
                            _controller.pause();
                          }
                          _play = !_play;
                          setState(() {});
                        }),
                      visible: !xianshikz,
                    ),
                    bottom: 5,
                    left: 0,
                  ),
                  Positioned(
                    child:Visibility(
                    child: IconButton(
                        icon: Icon(
                          Icons.fullscreen,
                          color: Colors.white,
                        ),
                        onPressed: () {
                          _controller.pause();
                          Navigator.push(context,
                              MaterialPageRoute(builder: (context) {
                            return FullScreen(
                              controller: _controller,
                              play: _play == true,
                            );
                          }));
                        }),
                    visible: !xianshikz,
                  ),
                    bottom: 5,
                    right: 5,
                  ),
                  Positioned(
                    child:Visibility(
                    child: IconButton(
                        icon: Icon(
                          _volume ? Icons.volume_up : Icons.volume_off,
                          color: Colors.white,
                        ),
                        onPressed: () {
                          setState(() {
                            if (_volume)
                              _controller.setVolume(0);
                            else
                              _controller.setVolume(1);
                            _volume = !_volume;
                          });
                        }),
                    visible: !xianshikz,
                  ),
                    bottom: 5,
                    right: 35,
                  )
                ],
              );
            }
            return LoadView();
          }),
    );
  }

  geWidth(VideoPlayerValue value) {
    var aspectRatio = value.aspectRatio;
    return 200 * aspectRatio;
  }

  @override
  void dispose() {
    super.dispose();
    if (_controller.value.isPlaying) {
      _controller.pause();
    }
    _controller.removeListener(_function);
    _controller.dispose();
  }
}
